package orm

import (
	"database/sql"
	"gitee.com/libwiki/go-zero-lib/package/orm/etc"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/schema"
	"sync"
	"time"
)

type Database struct {
	SqlDb  *sql.DB
	GormDb *gorm.DB
	config etc.Config
}

func NewDatabase(config etc.Config) *Database {
	sqlDb, gormDb := connect(config)
	return &Database{
		SqlDb:  sqlDb,
		GormDb: gormDb,
		config: config,
	}
}

var once sync.Once
var instance *Database

func NewSingleDatabase(config etc.Config) *Database {
	if instance == nil {
		once.Do(func() {
			sqlDb, gormDb := connect(config)
			instance = &Database{
				SqlDb:  sqlDb,
				GormDb: gormDb,
				config: config,
			}
		})
	}
	return instance
}

func connect(config etc.Config) (*sql.DB, *gorm.DB) {
	//var cstZone = time.FixedZone("CST", 8*3600) // 东八
	//time.Local = cstZone
	//time.LoadLocation("Asia/Shanghai")

	// 参考 https://github.com/go-sql-driver/mysql#dsn-data-source-name 获取详情
	var connectErr error
	conn, connectErr := gorm.Open(mysql.New(mysql.Config{
		DSN:                       config.Dsn, // DSN data source name
		DefaultStringSize:         255,        // string 类型字段的默认长度
		DisableDatetimePrecision:  true,
		SkipInitializeWithVersion: false,
	}), &gorm.Config{
		SkipDefaultTransaction:   true, // 跳过默认事务
		DisableNestedTransaction: false,
		NamingStrategy: schema.NamingStrategy{
			SingularTable: true, // 使用单数表名
		},
	})
	if connectErr != nil {
		panic(connectErr)
	}
	sqlDb, _ := conn.DB()
	sqlDb.SetMaxIdleConns(10)
	sqlDb.SetMaxOpenConns(100)
	sqlDb.SetConnMaxLifetime(time.Hour)
	return sqlDb, conn
}
